package com.elitedatai.mchtest.manage.controller;

import com.dji.sdk.cloudapi.log.FileUploadUpdateRequest;
import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.PaginationData;
import com.elitedatai.mchtest.common.model.CustomClaim;
import com.elitedatai.mchtest.manage.model.dto.DeviceLogsDTO;
import com.elitedatai.mchtest.manage.model.param.DeviceLogsCreateParam;
import com.elitedatai.mchtest.manage.model.param.DeviceLogsGetParam;
import com.elitedatai.mchtest.manage.model.param.DeviceLogsQueryParam;
import com.elitedatai.mchtest.manage.service.IDeviceLogsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URL;

import static com.elitedatai.mchtest.component.AuthInterceptor.TOKEN_CLAIM;


@RestController
@Slf4j
@RequestMapping("${url.manage.prefix}${url.manage.version}/workspaces")
public class DeviceLogsController {

    @Autowired
    private IDeviceLogsService deviceLogsService;

    /**
     * 根据查询参数分页获取设备上传的日志列表。
     * @param workspaceId 工作空间ID
     * @param deviceSn 设备序列号
     * @param param 查询参数
     * @return 分页的日志数据
     */
    @GetMapping("/{workspace_id}/devices/{device_sn}/logs-uploaded")
    public HttpResultResponse getUploadedLogs(DeviceLogsQueryParam param, @PathVariable("workspace_id") String workspaceId,
                                              @PathVariable("device_sn") String deviceSn) {
        PaginationData<DeviceLogsDTO> data = deviceLogsService.getUploadedLogs(deviceSn, param);
        return HttpResultResponse.success(data);
    }

    /**
     * 实时获取可上传的日志文件列表。
     * @param workspaceId 工作空间ID
     * @param deviceSn 设备序列号
     * @param param 查询参数
     * @return 日志文件列表
     */
    @GetMapping("/{workspace_id}/devices/{device_sn}/logs")
    public HttpResultResponse getLogsBySn(@PathVariable("workspace_id") String workspaceId,
                                          @PathVariable("device_sn") String deviceSn,
                                          DeviceLogsGetParam param) {
        return deviceLogsService.getRealTimeLogs(deviceSn, param.getDomainList());
    }

    /**
     * 向网关发起日志上传请求。
     * @param workspaceId 工作空间ID
     * @param deviceSn 设备序列号
     * @param request HTTP请求对象
     * @param param 日志创建参数
     * @return 请求结果
     */
    @PostMapping("/{workspace_id}/devices/{device_sn}/logs")
    public HttpResultResponse uploadLogs(@PathVariable("workspace_id") String workspaceId,
                                         @PathVariable("device_sn") String deviceSn,
                                         HttpServletRequest request, @RequestBody DeviceLogsCreateParam param) {

        CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);

        return deviceLogsService.pushFileUpload(customClaim.getUsername(), deviceSn, param);
    }

    /**
     * 取消日志文件上传。
     * @param workspaceId 工作空间ID
     * @param deviceSn 设备序列号
     * @param param 文件上传更新请求
     * @return 操作结果
     */
    @DeleteMapping("/{workspace_id}/devices/{device_sn}/logs")
    public HttpResultResponse cancelUploadedLogs(@PathVariable("workspace_id") String workspaceId,
                                                 @PathVariable("device_sn") String deviceSn,
                                                 @RequestBody FileUploadUpdateRequest param) {

        return deviceLogsService.pushUpdateFile(deviceSn, param);
    }

    /**
     * 删除上传历史记录。
     * @param workspaceId 工作空间ID
     * @param deviceSn 设备序列号
     * @param logsId 日志ID
     * @return 操作结果
     */
    @DeleteMapping("/{workspace_id}/devices/{device_sn}/logs/{logs_id}")
    public HttpResultResponse deleteUploadedLogs(@PathVariable("workspace_id") String workspaceId,
                                                 @PathVariable("device_sn") String deviceSn,
                                                 @PathVariable("logs_id") String logsId) {
        deviceLogsService.deleteLogs(deviceSn, logsId);
        return HttpResultResponse.success();
    }
    /**
     * 根据日志文件ID查询文件下载地址，并重定向到该地址进行下载。
     * @param workspaceId 工作空间ID
     * @param fileId 文件ID
     * @param logsId 日志ID
     * @param response HTTP响应对象
     * @return 文件下载地址或错误信息
     */
    @GetMapping("/{workspace_id}/logs/{logs_id}/url/{file_id}")
    public HttpResultResponse getFileUrl(@PathVariable(name = "workspace_id") String workspaceId,
                                         @PathVariable(name = "file_id") String fileId,
                                         @PathVariable(name = "logs_id") String logsId, HttpServletResponse response) {

        try {
            URL url = deviceLogsService.getLogsFileUrl(logsId, fileId);
            return HttpResultResponse.success(url.toString());
        } catch (Exception e) {
            log.error("Failed to get the logs file download address.");
            e.printStackTrace();
        }
        return HttpResultResponse.error("Failed to get the logs file download address.");
    }
}
